import { defineStore } from 'pinia'
import { ref } from 'vue'
import { api } from '@/utils/request'

export interface UserInfo {
  id: number
  username: string
  nickname: string | null
  role: string
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string | null>(localStorage.getItem('admin_token'))
  const userInfo = ref<UserInfo | null>(null)

  /**
   * 登录
   */
  async function login(username: string, password: string) {
    try {
      const response: any = await api.post('/auth/admin/login', {
        username,
        password
      })

      if (response.success && response.data) {
        token.value = response.data.token
        userInfo.value = response.data.admin
        localStorage.setItem('admin_token', response.data.token)
        return true
      }
      return false
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  /**
   * 登出
   */
  function logout() {
    token.value = null
    userInfo.value = null
    localStorage.removeItem('admin_token')
  }

  /**
   * 获取用户信息
   */
  async function getUserInfo() {
    try {
      const response: any = await api.get('/auth/me')
      if (response.success && response.data) {
        userInfo.value = response.data
        return response.data
      }
      return null
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
      throw error
    }
  }

  return {
    token,
    userInfo,
    login,
    logout,
    getUserInfo
  }
})
